package cn.wen.java.sql.ds;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Blob;
import java.sql.Clob;
import java.util.Date;

import org.apache.log4j.Logger;

import cn.wen.java.utils.Converter;

/**
 * Title: 数据单元
 * <p>
 * Description: 主要负责将装箱对象（obj）以各种基本类型返回。
 * <p>
 * Copyright: Copyright (c) 2010-2012
 * 
 * @author <a href="mailto:ct_wen@qq.com">ctwen</a>, 温承瑭
 * @version Revision: 1.0 Date: 2011/5/17 description：初完成。
 *          </P>
 */
public class DataCell {

    private final Logger log = Logger.getLogger(getClass());

    // ---------------------------------------------------------------------
    //
    // ---------------------------------------------------------------------

    public DataCell(Object obj) {
	super();
	setObject(obj);
    }

    public DataCell() {
	super();
    }

    // ---------------------------------------------------------------------
    //
    // ---------------------------------------------------------------------

    private Object obj;

    public void setObject(Object obj) {
	this.obj = obj;
    }

    // ---------------------------------------------------------------------
    //
    // ---------------------------------------------------------------------

    public Short toShort() {
	return convert(Short.class);
    }

    public Integer toInteger() {
	return convert(Integer.class);
    }

    public Long toLong() {
	return convert(Long.class);
    }

    public BigInteger toBigInteger() {
	return convert(BigInteger.class);
    }

    public Float toFloat() {
	return convert(Float.class);
    }

    public Double toDouble() {
	return convert(Double.class);
    }

    public BigDecimal toBigDecimal() {
	return convert(BigDecimal.class);
    }

    public Date toDate() {
	return convert(Date.class);
    }

    public Blob toBlob() {
	return convert(Blob.class);
    }

    public Clob toClob() {
	return convert(Clob.class);
    }

    public Object toObject() {
	return obj;
    }

    public String toJson() {
	if (this.obj instanceof Number) {
	    return obj.toString();
	}
	else {
	    return "\"" + obj.toString() + "\"";
	}
    }

    private <T> T convert(Class<T> clazz) {
	try {
	    return Converter.convert(obj, clazz);
	}
	catch (Exception e) {
	    log.warn(e.getMessage());
	}
	return null;
    }

    // ---------------------------------------------------------------------
    //
    // ---------------------------------------------------------------------

    @Override
    public String toString() {
	return toString("");
    }

    public String toString(String str) {
	return obj == null ? str : obj.toString();
    }

}
